package org.witsoft.demo.graphql.resovler;


import graphql.kickstart.tools.GraphQLQueryResolver;
import graphql.relay.Connection;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Component;
import org.witsoft.demo.graphql.entity.Author;
import org.witsoft.demo.graphql.entity.Book;
import org.witsoft.demo.graphql.extend.relay.ConnectionFactory;
import org.witsoft.demo.graphql.model.Result;
import org.witsoft.demo.graphql.repository.AuthorRepository;
import org.witsoft.demo.graphql.repository.BookRepository;

import java.util.Optional;

@Component
@RequiredArgsConstructor
public class RootQueryResolver implements GraphQLQueryResolver, InitializingBean {

    private final BookRepository bookRepository;
    private final AuthorRepository authorRepository;

    private ConnectionFactory<Book> bookConnectionFactory;

    @Getter
    private final UserQuery user;

    public Result<Book[]> findAllBooks(){
        Book[] array = bookRepository.findAll().stream().toArray(Book[]::new);
        return Result.success(array);
    }

    public Result<Author> findAuthorById(Long id){
        Optional<Author> optional = authorRepository.findById(id);
        if(!optional.isPresent()){
            return Result.error("作者不存在");
        }
        return Result.success(optional.get());
    }

    public Result<Book> findBookById(Long id){
        Optional<Book> optional = bookRepository.findById(id);
        if(!optional.isPresent()){
            return Result.error("书籍不存在");
        }
        return Result.success(optional.get());
    }

    public Connection<Book> books(int size, String cursor){
        return bookConnectionFactory.nextConnection(size, cursor);
    }

    @Override
    public void afterPropertiesSet()  {
        bookConnectionFactory = new ConnectionFactory<>(
                item->String.valueOf(item.getId()),
                request->{
                    PageRequest pageRequest = PageRequest.of (0, request.getSize());
                    Long id = StringUtils.isEmpty(request.getKey()) ? 0: Long.parseLong(request.getKey());
                    return bookRepository.findByIdGreaterThan(id, pageRequest);
                }
        );
    }

}
